//
//  GradingView.swift
//  FeastBooking
//
//  Created by Imon on 2017/11/9.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit

class GradingView: UIView {
    
    var grade: Int = 0
    
    let normalImg = UIImage(named: "star")
    
    let selectedImg = UIImage(named: "star_choose")
    
    let stars: [UIImageView] = {
        var imgViews: [UIImageView] = []
        for i in 0...4 {
            let imgView = UIImageView()
            imgView.contentMode = .scaleAspectFill
            imgView.layer.masksToBounds = true
            imgViews.append(imgView)
        }
        return imgViews
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        for i in 0...stars.count - 1 {
            stars[i].image = normalImg
            self.addSubview(stars[i])
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func touchAt(index: Int) {
        if grade == (index + 1) {
            for i in 0...index {
                stars[i].image = normalImg
            }
            grade = 0
        } else {
            for i in 0...index {
                stars[i].image = selectedImg
            }
            grade = index + 1
            if index < stars.count - 1 {
                for i in index + 1...stars.count - 1 {
                    stars[i].image = normalImg
                }
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self)
            for i in 0...stars.count - 1 {
                if stars[i].frame.contains(point) {
                    touchAt(index: i)
                    break
                }
            }
        }
    }
    
    override func layoutSubviews() {
        let starWidth: CGFloat = self.bounds.height
        let gap: CGFloat = (self.bounds.width - 5 * starWidth) / 4
        for i in 0...stars.count - 1 {
            stars[i].frame = CGRect(x: (starWidth + gap) * CGFloat(i), y: 0, width: starWidth, height: starWidth)
        }
    }
}
